package design.behavior_state;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * 状态模式
 */
public class DemoState {
    @Test
    public void test() {
        Context context = new Context();
        List<OrderState> list = new ArrayList<>();
        list.add(new OrderPending(context));
        list.add(new OrderProcessing(context));
        list.add(new OrderEnd(context));
        context.setCurrentState(list.get(1));
        context.setOrderStateList(list);
        context.changeOrderState();
        context.changeOrderState();
        context.changeOrderState();
    }
    //抽象订单状态类
    public abstract class OrderState {
        Context context;
        public OrderState(Context context){
            this.context = context;
        }
        public abstract void handle();
    }
    //待处理订单
    public  class OrderPending extends OrderState {
        public OrderPending(Context context) {
            super(context);
        }
        @Override
        public void handle() {
            System.out.println("执行待处理业务逻辑");
            context.setCurrentState(context.getNext());
        }
    }
    //进行中订单
    public  class OrderProcessing extends OrderState {
        public OrderProcessing(Context context) {
            super(context);
        }
        @Override
        public void handle() {
            System.out.println("执行进行中业务逻辑");
            context.setCurrentState(context.getNext());
        }
    }
    //已结束订单
    public  class OrderEnd extends OrderState {
        public OrderEnd(Context context) {
            super(context);
        }

        @Override
        public void handle() {
            System.out.println("执行已结束业务逻辑");
        }
    }
    //定义一个上下文管理环境
    public  class Context {

        private OrderState currentState;
        private List<OrderState> orderStateList;


        public void setCurrentState(OrderState currentState) {
            this.currentState = currentState;
        }

        public void setOrderStateList(List<OrderState> orderStateList) {
            this.orderStateList = orderStateList;
        }

        public void changeOrderState() {
            currentState.handle();
        }
        public OrderState getNext(){
            OrderState nextOrderState = null;
            int currentStateIndex=orderStateList.indexOf(currentState);
            if (orderStateList.size() > currentStateIndex) {
                nextOrderState = orderStateList.get(currentStateIndex + 1);
            }
            return nextOrderState;
        }
    }

}
